package edu.gatech.ors.mrsim.helpers;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Calendar;

/**
 * Utility class for formatting Strings
 * 
 * @author Andrey K
 * 
 */
public class StringUtil {

    /**
     * Basic date formatting method.
     * 
     * @param time
     *            Calendar from which to extract things
     * @return String with formatting date in format "{month}/{day}/{year} -
     *         {hour}:{minute}:{second}
     */
    public static String getFormattedTime(Calendar time) {
	return time.get(Calendar.MONTH) + "/" + time.get(Calendar.DATE) + "/"
		+ time.get(Calendar.YEAR) + " - "
		+ time.get(Calendar.HOUR_OF_DAY) + ":"
		+ time.get(Calendar.MINUTE) + ":" + time.get(Calendar.SECOND);
    }

    /**
     * Basic date formatting method for milliseconds.
     * 
     * @param time
     *            Time in milliseconds from which to extract things
     * @return String with formatting date in format "{month}/{day}/{year} -
     *         {hour}:{minute}:{second}
     */
    public static String getFormattedTime(long milli) {
	Calendar calendar = Calendar.getInstance();
	calendar.setTimeInMillis(milli);
	return getFormattedTime(calendar);
    }

    /**
     * Basic date formatting method for current time.
     * 
     * @return String with formatting date in format "{month}/{day}/{year} -
     *         {hour}:{minute}:{second}
     */
    public static String getFormattedTime() {
	return getFormattedTime(Calendar.getInstance());
    }

    /**
     * Simply retrieves the StackTrace that would have resulted from
     * printStackTrace as a String.
     * 
     * @param from
     *            the Throwabe to get stack trace from
     * @return String version of Stack Trace
     */
    public static String getStackTrace(Throwable from) {
	StringWriter sWriter = new StringWriter();
	PrintWriter writer = new PrintWriter(sWriter);
	from.printStackTrace(writer);
	String value = sWriter.toString();
	try {
	    sWriter.close();
	    writer.close();
	} catch (IOException e) {
	    e.printStackTrace();
	}
	return value; // stack trace as a string
    }
}
